package com.deyang.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deyang.workflow.constant.Constants;
import com.deyang.workflow.entity.WorkOrderBase;
import com.deyang.workflow.entity.WorkOrderDetails;
import com.deyang.workflow.entity.WorkOrderStep;
import com.deyang.workflow.mapper.WorkOrderBaseMapper;
import com.deyang.workflow.mapper.WorkOrderDetailsMapper;
import com.deyang.workflow.mapper.WorkOrderStepMapper;
import com.deyang.workflow.service.IWorkOrderDetailsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deyang.workflow.service.IWorkOrderStepService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * <p>
 * 工单详情记录表 服务实现类
 * </p>
 *
 * @author zhanghuaiyu
 * @since 2021-07-01
 */
@Service
@Slf4j
@Transactional
public class WorkOrderDetailsServiceImpl extends ServiceImpl<WorkOrderDetailsMapper, WorkOrderDetails> implements IWorkOrderDetailsService {

    @Autowired
    private WorkOrderDetailsMapper workOrderDetailsMapper;

    @Autowired
    private WorkOrderBaseMapper workOrderBaseMapper;

    @Autowired
    private WorkOrderStepMapper workOrderStepMapper;

    @Override
    public List<WorkOrderDetails> transferRecord(String workOrderId) {
        //根据工单id查询对应的工单流程记录
        QueryWrapper<WorkOrderDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_order_id", workOrderId);
        List<WorkOrderDetails> list = workOrderDetailsMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public List<WorkOrderDetails> queryEventList(String sign, String user) {
        //根据传入的sign值和用户查询已处理、未处理、已提交的数据
        QueryWrapper<WorkOrderDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("STATUS", sign).eq("creator", user);
        List<WorkOrderDetails> list = workOrderDetailsMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public WorkOrderDetails queryWorkOrder(Map<String, String> map) {

        log.info("==============================================" + "进入查询工单详情信息表" + map);
        //根据传入的查询状态和工单编号以及创建人信息查询对应的工单信息
        WorkOrderDetails workOrderDetails = null;
        try {
            QueryWrapper<WorkOrderDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", map.get("status")).eq("work_order_id", map.get("workOrderId")).eq("creator", map.get("creator"));
            workOrderDetails = workOrderDetailsMapper.selectOne(queryWrapper);
            //判断是否有图片地址信息
            if (null != workOrderDetails && null != workOrderDetails.getPhotoPath()) {
                List<String> list = new ArrayList<>();
                //获取文件下的所有文件
                File file = new File(workOrderDetails.getPhotoPath());
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    File fs = files[i];//获取数组中的第i个
                    if (!fs.isDirectory()) {//如果不是文件夹，则获取对应的文件名
                        list.add(GetImageStr(workOrderDetails.getPhotoPath() + "\\" + fs.getName()));
                    }

                }
                workOrderDetails.setListImg(list);
            }
            log.info("===========================================" + "查询工单详情表信息成功");
        } catch (Exception e) {
            log.error("===========================================" + "查询工单详情表失败" + e.getMessage());
        }

        return workOrderDetails;
    }

    @Override
    public void sendOrder(String workOrderId, String templateCode) {
        //1.根据模板编号获取模板步骤信息
        QueryWrapper<WorkOrderStep> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_code", templateCode).eq("status", "1");
        List<WorkOrderStep> workOrderSteps = workOrderStepMapper.selectList(queryWrapper);

        //2.获取工单基本信息
        WorkOrderBase workOrderBase = workOrderBaseMapper.selectById(workOrderId);

        //3.获取工单编号获取没有处理工单步骤表的信息
        QueryWrapper<WorkOrderDetails> detailsQueryWrapper = new QueryWrapper<>();
        detailsQueryWrapper.eq("work_order_id", workOrderId).eq("status", "0");
        WorkOrderDetails workOrderDetails = workOrderDetailsMapper.selectOne(detailsQueryWrapper);


        if (null != workOrderSteps && workOrderSteps.size() > 0) {
            WorkOrderDetails details = new WorkOrderDetails();
            WorkOrderStep nextStep = new WorkOrderStep();
            //遍历list，判断集合中id最小的数据则默认为是第一级分配人员
            int min = workOrderSteps.stream().mapToInt(WorkOrderStep -> WorkOrderStep.getId()).min().getAsInt();
            //遍历集合，获取id最小的集合中的数据
            WorkOrderStep step = workOrderSteps.stream().filter(o -> o.getId() == min).findAny().orElse(null);
            //根据模板步骤的唯一id获取下一节点的数据
            if (null != step && null != step.getTemplateUuid()) {
                nextStep = workOrderSteps.stream().filter(o -> step.getTemplateUuid().equals(o.getParentId())).findAny().orElse(null);
            }
            //获取到模板步骤的节点名称、节点地址、处理方式、通知方式、是否可协同、是否可驳回
            if (null != step) {
                details.setNodeName(step.getNodeName());//节点名称
                details.setPageAddress(step.getNodeAddress());//节点地址
                details.setCreateTime(new Date());//创建时间
                details.setWorkOrderId(workOrderBase.getWorkOrderId());//工单编号
                details.setWorkOrderName(workOrderBase.getWorkOrderName());//工单名称
                details.setStatus("0");//工单状态，0为未处理，1为已处理
                //处理方式：候选人、部门、岗位，暂定只有候选人，默认候选人为0，部门为1，岗位为2
                if ("0".equals(step.getProcessMode())) {
                    details.setProcessMode(Constants.CANDIDATE);//处理方式
                    details.setCreator(step.getCandidate());//当前处理人，即为需要发送短信通知的人，并且在h5的未处理中能够看见
                    workOrderBase.setDutyPerson(step.getCandidate());//设置工单基本信息的当前处理人最新处理人信息
                    workOrderDetails.setStatus("1");//设置初始工单的状态为已处理
                    if (null != nextStep && null != nextStep.getCandidate()) {
                        details.setNextCreator(nextStep.getCandidate());//下级处理人
                    }
                }
                if ("01".equals(step.getProcessMode())) {

                }
                if ("02".equals(step.getProcessMode())) {

                }

                //判断模板此节点是否可协同和是否可驳回
                if (null != step.getSynergyStatus()) {//是否可协同
                    details.setSynergyStatus(step.getSynergyStatus());
                }
                if (null != step.getRejectStatus()) {//是否可驳回
                    details.setRejectStatus(step.getRejectStatus());
                }
            }

            //首先更新原有的工单步骤状态为已处理
            workOrderDetailsMapper.updateById(workOrderDetails);
            //在更新工单步骤表信息
            workOrderDetailsMapper.insert(details);
            //在更新工单基础表信息
            workOrderBaseMapper.updateById(workOrderBase);


            /*
             *
             *根据催办时间需要添加短信功能，目前短信暂未开通
             * */

        }

    }

    @Override
    public WorkOrderDetails queryWorkOrder(String workOrderId) {
        //根据工单编号查询工单步骤信息，此方法主要用来查询手动派单的工单的基本步骤
        QueryWrapper<WorkOrderDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("work_order_id", workOrderId);
        WorkOrderDetails workOrderDetails = workOrderDetailsMapper.selectOne(queryWrapper);
        return workOrderDetails;
    }


    /**
     * 参数为照片的目录路径+文件名称+文件后缀
     *
     * @param imgFile
     * @return
     */
    public String GetImageStr(String imgFile) {//将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        log.info("=============================" + "获取到的图片地址为" + imgFile);
        InputStream in = null;
        byte[] data = null;

        //读取图片字节数组
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            log.error("=======================" + "图片转换失败" + e.getMessage());
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64编码过的字节数组字符串
    }

}
